19. Automatic Variables

Note

The below information is extensively based in information taken from the PowerShell® Notes for Professionals book. I plan to extend this information based on my day to day usage of the language.

Automatic Variables are created and maintained by Windows PowerShell. One has the ability to call a variable just about any name in the book; The only exceptions to this are the variables that are already being managed by PowerShell. These variables, without a doubt, will be the most repetitious objects you use in PowerShell next to functions (like $? - indicates Success/ Failure status of the last operation)

19.1: $OFS

Variable called Output Field Separator contains string value that is used when converting an array to a string. By default $OFS = " " ( a space ), but it can be changed:

1
2
3
4
5
6
$array = 1 , 2 , 3
"$array" # default OFS will be used
1 2 3
$OFS = ",." # we change OFS to comma and dot
"$array"
1 ,.2,.3

19.2: $?

Contains status of the last operation. When there is no error, it is set to True:

1
2
3
4
Write-Host "Hello"
Hello
$?
True

If there is some error, it is set to False:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
wrt-host
wrt-host : The term 'wrt-host' is not recognized as the name of a cmdlet, function, script file, or
operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.
At line: 1 char: 1
+ wrt-host
+ ~~~~~~~~
+ CategoryInfo : ObjectNotFound: (wrt-host:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
1
2
$?
False

19.3: $null

$null is used to represent absent or undefined value.

$null can be used as an empty placeholder for empty value in arrays:

1
2
3
$array = 1 , "string", $null
$array.Count
3

When we use the same array as the source for ForEach-Object , it will process all three items (including $null):

1
2
3
4
$array | ForEach-Object {"Hello"}
Hello
Hello
Hello

Be careful! This means that ForEach-Object WILL process even $null all by itself:

1
2
$null | ForEach-Object {"Hello"} # THIS WILL DO ONE ITERATION !!!
Hello

Which is very unexpected result if you compare it to classic foreach loop:

1
2
foreach($i in $null) {"Hello"} # THIS WILL DO NO ITERATION
C:\>

19.4: $error

Array of most recent error objects. The first one in the array is the most recent one:

1
2
3
4
5
6
7
throw "Error" # resulting output will be in red font
Error
At line: 1 char: 1
+ throw "Error"
+ ~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (Error:String) [], RuntimeException
+ FullyQualifiedErrorId : Error
1
2
3
4
5
6
7
$error[ 0 ] # resulting output will be normal string (not red )
Error
At line: 1 char: 1
+ throw "Error"
+ ~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (Error:String) [], RuntimeException
+ FullyQualifiedErrorId : Error

Usage hints: When using the $error variable in a format cmdlet (e.g. format-list), be aware to use the -Force switch. Otherwise the format cmdlet is going to output the $errorcontents in above shown manner.

Error entries can be removed via e.g. Error.Remove(Error[ 0 ]).

19.5: $pid

Contains process ID of the current hosting process.

1
2
$pid
26080

19.6: Boolean values

$true and $false are two variables that represent logical TRUE and FALSE.

Note that you have to specify the dollar sign as the first character (which is different from C#).

1
2
3
4
$boolExpr = "abc".Length -eq 3 # length of "abc" is 3, hence $boolExpr will be True
if($boolExpr -eq $true){
  "Length is 3"
}
1
2
3
# result will be "Length is 3"
$boolExpr -ne $true
#result will be False

Notice that when you use boolean true/false in your code you write $true or $false, but when Powershell returns a boolean, it looks like True or False

19.7: $_ / $PSItem

Contains the object/item currently being processed by the pipeline.

1
2
3
4
5
6
1 .. 5 | % { Write-Host "The current item is $_" }
The current item is 1
The current item is 2
The current item is 3
The current item is 4
The current item is 5

$PSItem and $_ are identical and can be used interchangeably, but $_ is by far the most commonly used.

19.8: $PSVersionTable

Contains a read-only hash table (Constant, AllScope) that displays details about the version of PowerShell that is running in the current session.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$PSVersionTable #this call results in this:
Name Value
---- -----
PSVersion 5.0.10586.117
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.10586.117
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1

The fastest way to get a version of PowerShell running:

1
2
3
4
5
$PSVersionTable.PSVersion
# result :
Major Minor Build Revision
----- ----- ----- --------
5 0 10586 117